using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using DG.Tweening;
using Enum;
using SO;
using Struct;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Serialization;
using UnityEngine.UI;

namespace Entity {

    public partial class EntityController : MonoBehaviour, IHealthSystem {

        
        /// <summary>
        /// 跑
        /// </summary>
        public string AnimationName_run = "run";

        /// <summary>
        /// 空闲
        /// </summary>
        public string AnimationName_idle = "idle";

        /// <summary>
        /// 走路
        /// </summary>
        public string AnimationName_move = "move";

        /// <summary>
        /// 普通攻击
        /// </summary>
        public string AnimationName_phyattack = "phyattack";

        /// <summary>
        /// 受击
        /// </summary>
        public string AnimationName_behit = "behit";

        /// <summary>
        /// 闪避
        /// </summary>
        public string AnimationName_dodge = "dodge";

        /// <summary>
        /// 死亡
        /// </summary>
        public string AnimationName_die = "die";

        /// <summary>
        /// 出现
        /// </summary>
        public string AnimationName_show = "show";

        /// <summary>
        /// 使用技能
        /// </summary>
        public string AnimationName_skill1 = "skill1";

        public virtual void InitEnemy(CharactarModelMappingConfigSO charactarModelMappingConfigSo, float strengthCoefficient) {
            configSo = charactarModelMappingConfigSo;
            currentTeam = EnumTeamType.Enemy;
            Dictionary<EnumPropertiesType, PropertiesStruct> propertiesDict = GetStrongerProperties(configSo.basePropertiesDict, strengthCoefficient);
            OnInitFightProperties(new FightProperties(propertiesDict, false, this));
            InitFSM();
            CharacverCanvasState(true);
            UpdateHealthSlider();
            CharacterCanvas.Go_Buffs.RefreshBuffs(this);
            RemoveAllBuffs();
        }

        /// <summary>
        /// 获取 计算 强度系数后的属性
        /// </summary>
        /// <param name="configSoBasePropertiesDict"></param>
        /// <param name="strengthCoefficient"></param>
        /// <returns></returns>
        private Dictionary<EnumPropertiesType, PropertiesStruct> GetStrongerProperties(Dictionary<EnumPropertiesType, PropertiesStruct> configSoBasePropertiesDict, float strengthCoefficient) {
            Dictionary<EnumPropertiesType, PropertiesStruct> newPropertiesDict = new Dictionary<EnumPropertiesType, PropertiesStruct>();
            foreach (var key in configSoBasePropertiesDict.Keys) {
                PropertiesStruct pro = configSoBasePropertiesDict[key];
                //如果是 mp 或者 攻击恢复mp 则不参与计算
                if (pro.propertiesType != EnumPropertiesType.MaxMP && pro.propertiesType != EnumPropertiesType.NormalAttackGetMP) {
                    pro.value = (int)(pro.value * strengthCoefficient);
                }

                newPropertiesDict[key] = pro;
            }

            return newPropertiesDict;
        }


        public float PlayAnimation(string animationName, bool isLoop = false) {
            if (!this) {
                return 0;
            }

        }

        public float GetAnimationDuration(string animationName) {
        }

        public void CharacverCanvasState(bool state) {
        }


        /// <summary>
        /// 获取 当前角色的 位面位置
        /// </summary>
        /// <returns></returns>
        public Vector3 GetPlaneOfBitPosition() {
            Vector3 position = this.transform.position;
            if (currentTeam == EnumTeamType.Enemy) {
                position = position + Vector3.left * 5f;
            } else {
                position = position + Vector3.right * 5f;
            }

            return position;
        }

        public void SetSortingGroup(int value) {
            GetComponent<SortingGroup>().sortingOrder = value;
        }


#region FSM

        private FSM<EnumCharacterState> fsm;

        public FSM<EnumCharacterState> FSM => fsm;

        public virtual void InitFSM() {
            fsm = new FSM<EnumCharacterState>();
            FSM_Idle(); //空闲
            FSM_Run(); //跑步
            FSM_NormalAttack(); //普通攻击
            FSM_UseSkill(); //使用技能
            FSM_BeHit(); //被攻击
            FSM_Dodge(); //闪避
            FSM_Die(); //死亡
            fsm.StartState(EnumCharacterState.Idle); // 将初始状态设置为Idle状态
        }

        private void FSM_Dodge() {
            fsm.State(EnumCharacterState.Evasion)
               .OnEnter(async () => {
                   GameLayerEffectManager.Instance.ShowDamageTipAnimation($"Miss", GetShowTipPosition(), 2);
                   await UniTaskTools.Delay(PlayAnimation(AnimationName_dodge, false));
                   fsm.ChangeState(fsm.PreviousStateId);
               })
               .OnUpdate(() => { });
        }

        private void FSM_Idle() {
            fsm.State(EnumCharacterState.Idle)
               .OnEnter(() => {
                   PlayAnimation(AnimationName_idle, true);
               })
               .OnUpdate(() => { });
        }

        private void FSM_Run() {
            fsm.State(EnumCharacterState.Run)
               .OnEnter(() => {
                   PlayAnimation(AnimationName_run, true);
               })
               .OnUpdate(() => { });
        }


        private void FSM_NormalAttack() {
            fsm.State(EnumCharacterState.NormalAttack)
               .OnEnter(async () => {
                   this.Delay(PlayAnimation(AnimationName_phyattack), () => {
                       if (IsAlive) {
                           ChangeState(EnumCharacterState.Idle);
                       }
                   });

               })
               .OnUpdate(() => { });
        }

        private void FSM_BeHit() {
            fsm.State(EnumCharacterState.BeHit)
               .OnEnter(async () => {

                   this.Delay(PlayAnimation(AnimationName_behit), () => {
                       if (IsAlive) {
                           ChangeState(fsm.PreviousStateId);
                           // ChangeState(EnumCharacterState.Idle);
                       } else {
                           ChangeState(EnumCharacterState.Die);
                       }
                   });

               })
               .OnUpdate(() => { });
        }

        private void FSM_UseSkill() {
            fsm.State(EnumCharacterState.UseSkill)
               .OnEnter(async () => {
                   this.Delay(PlayAnimation(AnimationName_skill1), () => {
                       if (IsAlive) {
                           ChangeState(EnumCharacterState.Idle);
                       }
                   });

               })
               .OnUpdate(() => { });
        }


        private void FSM_Die() {
            fsm.State(EnumCharacterState.Die)
               .OnEnter(async () => {
                   // isDeath = true;
                   if (isEnemy) {
                       LogTools.LogGreen($"敌人  {gameObject.name} 死亡");
                       CharacverCanvasState(false);
                   }

                   await UniTaskTools.Delay(PlayAnimation(AnimationName_die));
                   if (isEnemy) {
                       gameObject.RecycleToPool();
                   }

               })
               .OnUpdate(() => { });
        }


#endregion


        public Vector3 GetShowTipPosition() {
            return new Vector3(transform.position.x, transform.position.y + 5);
        }
    }

}